package org.xsk.structure.stack;

import lombok.Data;

@Data
public class ArrayStack {
    private int maxStack;
    private int[] stack;
    private int top = -1;

    public ArrayStack(int maxStack) {
        this.maxStack = maxStack;
        stack = new int[maxStack];
    }

    public boolean isFull() {
        return this.top == this.maxStack - 1;
    }

    public boolean isEmpty() {
        return this.top == -1;
    }

    public void push(int val) {
        if (isFull()) {
            throw new RuntimeException("此栈已满");
        }
        top++;
        stack[top] = val;
    }

    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("空栈，未找到数据");
        }
        int val = stack[top];
        top--;
        return val;
    }

    /**
     * 打印栈信息
     */
    public void list() {
        if (isEmpty()) {
            throw new RuntimeException("空栈，未找到数据");
        }

        for (int i = 0; i < stack.length; i++) {
            System.out.printf("stach[%d]=[%d\n]", i, stack[i]);
        }
    }

    /**
     * 栈内数据的长度
     * 
     * @return
     */
    public int valLength() {
        return top + 1;
    }

    /**
     * 判断是否运算符
     * 
     * @param v
     * @return
     */
    public boolean isOper(char v) {
        return v == '+' || v == '-' || v == '*' || v == '/';
    }

    /**
     * 判断运算符的 优先级
     * 
     * @param oper
     * @return
     */
    public int priority(int oper) {
        if (oper == '*' || oper == '/') {
            return 1;
        } else if (oper == '+' || oper == '-') {
            return 0;
        } else {
            return -1;
        }
    }

    /**
     * 栈当前位置的值，栈顶
     * 
     * @return
     */
    public int peek() {
        return this.stack[top];
    }

    /**
     * 栈 的容量
     * 
     * @return
     */
    public int stackLength() {
        return this.stack.length;
    }

    public int calculate(int num1, int num2, int oper) {
        int result = 0;
        switch (oper) {
            case '+':
                result = num1 + num2;
                break;
            case '-':
                result = num2 - num1;
                break;
            case '*':
                result = num2 * num1;
                break;
            case '/':
                result = num2 / num1;
                break;
            default:
                break;
        }
        return result;
    }

}
